//
//  MyselfController.m
//  Otaku
//
//  Created by lanou3g on 16/5/12.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "MyselfController.h"

#import "EditUserInfoController.h"
#import "AppIfnoController.h"
#import "SendFeedbackController.h"
@interface MyselfController ()
/// 用户名
@property (nonatomic, copy) NSString *userName;
/// 皮肤改变的开关
@property (nonatomic, weak) UISwitch *shakeCanChangeSkinSwitch;
/// 当前皮肤颜色
@property (nonatomic, copy) NSString *currentSkinModel;
/// 缓存大小
@property (nonatomic, assign) CGFloat cacheSize;
// 改变模式的按钮
@property (nonatomic, weak) UISwitch *changeSkinSwitch;


@end
CGFloat const footViewHeight = 30;
@implementation MyselfController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 设置没边距
    self.tableView.contentInset = UIEdgeInsetsMake(CGRectGetMaxY(self.navigationController.navigationBar.frame) + 30, 0, 0, 0);
    
    self.title = @"我";
    
}
// 将要显示的时候发送通知
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upDateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self upDateSkinModel];
}
// 将要消失的时候移除通知
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
    
}

#pragma mark 更新皮肤模式 接到模式切换的通知后会调用此方法

- (void)upDateSkinModel {
    // 获取当前的模式
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    // 判断进行更改
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.tableView.backgroundColor = [UIColor blackColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }else {
        self.tableView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    // 刷新 UI
    [self.tableView reloadData];
    
}

// 缓存数据

- (void)caculateCacheSize {
    float imageCache = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float sqliteCache = [fileManager attributesOfItemAtPath:path error:nil].fileSize/1024.0/1024.0;
    
    self.cacheSize = imageCache + sqliteCache;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 2;
    }
    
    
    
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return footViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 100;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] init];
    footView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, footViewHeight);
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1);
    [footView addSubview:lineView1];
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.frame = CGRectMake(0, footViewHeight - 1, [UIScreen mainScreen].bounds.size.width, 1);
    [footView addSubview:lineView2];
    if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
        footView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        lineView1.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        lineView2.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    } else {
        footView.backgroundColor = [UIColor blackColor];
        lineView1.backgroundColor = [UIColor blackColor];
        lineView2.backgroundColor = [UIColor blackColor];
    }
    if (section==2) {
        [lineView2 removeFromSuperview];
    }
    return footView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    if (indexPath.section == 0) {
        CGFloat cellHeight = 100;
        CGFloat kScreenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat margin = 10;
        
        UIView *lineView = [[UIView alloc] init];
        lineView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1);
        [cell addSubview:lineView];
        UIImageView *avatarImageView = [[UIImageView alloc] init];
        avatarImageView.frame =CGRectMake(margin, margin, cellHeight - 2*margin, cellHeight - 2*margin);
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"headerImage"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        if (image == nil) {
            image = [UIImage imageNamed:@"head_bg.png"];
            // 将图片写入数据库 PNG格式的
            [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
        }
        avatarImageView.image = image;
        avatarImageView.layer.cornerRadius = avatarImageView.frame.size.width * 0.5;
        avatarImageView.layer.masksToBounds = YES;
        [cell addSubview:avatarImageView];
        
        UILabel *nameLabel = [[UILabel alloc] init];
        CGFloat nameLabelHeight = 21.5;
        nameLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:UserNameKey];
        nameLabel.font = [UIFont systemFontOfSize:18];
        if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
            nameLabel.textColor = [UIColor blackColor];
            lineView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        } else {
            nameLabel.textColor = [UIColor grayColor];
            lineView.backgroundColor = [UIColor blackColor];
        }
        nameLabel.frame = CGRectMake(CGRectGetMaxX(avatarImageView.frame) + margin, avatarImageView.frame.origin.y +avatarImageView.frame.size.height*0.5 - nameLabelHeight-0.5*margin, kScreenWidth - 3*margin -avatarImageView.frame.size.width, nameLabelHeight);
        [cell addSubview:nameLabel];
        
        UILabel *contentLabel = [[UILabel alloc] init];
        CGFloat contentLabelHeight = 17.5;
        contentLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:UserSignatureKey];
        
        contentLabel.font = [UIFont systemFontOfSize:14];
        contentLabel.textColor = [UIColor grayColor];
        contentLabel.frame = CGRectMake(CGRectGetMaxX(avatarImageView.frame) + margin, avatarImageView.frame.origin.y +avatarImageView.frame.size.height*0.5+0.5*margin, kScreenWidth - 3*margin -avatarImageView.frame.size.width, contentLabelHeight);
        contentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [cell addSubview:contentLabel];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.section == 1) {

        if (indexPath.row == 0) {
            cell.textLabel.text = @"夜间模式";
            // 如果附件为空
            if (cell.accessoryView == nil) {
                UISwitch *changeSkinSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 51, 31)];
                self.changeSkinSwitch = changeSkinSwitch;
                [changeSkinSwitch addTarget:self action:@selector(switchDidChange:) forControlEvents:UIControlEventValueChanged];
                
                cell.accessoryView = changeSkinSwitch;
            }
           
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"清除缓存";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.1f MB",self.cacheSize];
        }
        
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"反馈";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else if(indexPath.row == 1) {
            cell.textLabel.text = @"关于";
            // 设置 cell 的样式
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
    }
    
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        cell.backgroundColor = [UIColor colorWithRed:35/255.0 green:32/255.0 blue:36/255.0 alpha:1.0];
        cell.textLabel.textColor = [UIColor colorWithRed:111/255.0 green:109/255.0 blue:112/255.0 alpha:1.0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.changeSkinSwitch.on = YES;
    } else {//夜间模式
        cell.backgroundColor =[UIColor whiteColor];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        self.changeSkinSwitch.on = NO;
    }

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) {
       
        
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] cleanDisk];
        [self.tableView reloadData];
        [self performSelectorOnMainThread:@selector(clearMemorySuccess) withObject:nil waitUntilDone:YES];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"0.0MB"];
    } else if (indexPath.section == 2 && indexPath.row == 0) {
        [self.navigationController pushViewController:[[SendFeedbackController alloc] init] animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 1) {
        [self.navigationController pushViewController:[[AppIfnoController alloc] init] animated:YES];
    } else if (indexPath.section == 0 && indexPath.row == 0) {
        [self.navigationController pushViewController:[[EditUserInfoController alloc] init] animated:YES];
    }
}
// 清除缓存提示框
- (void)clearMemorySuccess {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"清除缓存成功" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
   
    [self presentViewController:alertController animated:YES completion:nil];
    
    
}
// 模式开关的点击事件
- (void)switchDidChange:(UISwitch *)theSwitch {
    if (theSwitch == self.changeSkinSwitch) {
        if (theSwitch.on == YES) {//切换至夜间模式
           // NSUserDefaults提供的默认系统交互的编程接口
            [[NSUserDefaults standardUserDefaults] setObject:NightSkinModelValue forKey:CurrentSkinModelKey];
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:DaySkinModelValue forKey:CurrentSkinModelKey];
        }
        //同步方法，它是自动调用的周期间隔，保持在内存高速缓存中的用户的默认数据库同步执行
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        // 发送通知通过 Name
        [[NSNotificationCenter defaultCenter] postNotificationName:SkinModelDidChangedNotification object:self];
        
    }

}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
